package cn.dubito.sshl.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.dubito.sshl.common.PageModel;
import cn.dubito.sshl.dao.notice.dao.NoticeDao;
import cn.dubito.sshl.domain.Notice;
import cn.dubito.sshl.exception.SSHLException;
import cn.dubito.sshl.idx.notice.NoticeIndexDao;
import cn.dubito.sshl.service.NoticeService;


/**
 * NoticeServiceImpl
 */
@Service("noticeService")
@Transactional(readOnly=false)
public class NoticeServiceImpl implements NoticeService {
	/** 注入 */
	@Resource(name="noticeDao")
	private NoticeDao noticeDao;
	@Resource(name="noticeIndexDao")
	private NoticeIndexDao noticeIndexDao;
	
	/**
	 * 分页查询公告
	 * @param pageModel
	 * @return 集合
	 */
	@Transactional(readOnly=true)
	public List<Notice> getNoticeByPage(PageModel pageModel){
		try{
			return noticeDao.getNoticeByPage(pageModel);
		}catch(Exception ex){
			throw new SSHLException("分页查询公告时出现异常 ！", ex);
		}
	}
	/**
	 * 添加公告
	 * @param notice
	 */
	public void saveNotice(Notice notice){
		try{
			/** 保存到数据库 */
			noticeDao.save(notice);
			/** 保存到索引库 */
			noticeIndexDao.saveNotice(notice);
		}catch(Exception ex){
			throw new SSHLException("添加公告时出现异常 ！", ex);
		}
	}
	/**
	 * 根据主键id查询公告
	 * @param id
	 * @return
	 */
	public Notice getNotice(int id){
		try{
			return noticeDao.get(Notice.class, id);
		}catch(Exception ex){
			throw new SSHLException("根据主键id查询公告时出现异常 ！", ex);
		}
	}
	/**
	 * 修改公告
	 * @param notice
	 */
	public void updateNotice(Notice notice){
		try{
			// 获取持久化状态对象
			Notice n = getNotice(notice.getId());
			n.setTitle(notice.getTitle());
			n.setContent(notice.getContent());
			// 修改索引库
			noticeIndexDao.updateNotice(notice);
		}catch(Exception ex){
			throw new SSHLException("修改公告时出现异常 ！", ex);
		}
	}
	/**
	 * 删除公告
	 * @param id
	 */
	public void deleteNotice(int id){
		try{
			// 获取持久化状态对象
			noticeDao.delete(getNotice(id));
			// 删除索引库中数据
			noticeIndexDao.delete("id", String.valueOf(id));
		}catch(Exception ex){
			throw new SSHLException("删除公告时出现异常 ！", ex);
		}
	}
	/**
	 * 全文检索
	 * @param keyword
	 * @param pageModel
	 * @return
	 */
	public List<Notice> search(String keyword, PageModel pageModel){
		try{
			return noticeIndexDao.getNoticeByPage(keyword, pageModel, noticeDao);
		}catch(Exception ex){
			throw new SSHLException("全文检索时出现异常 ！", ex);
		}
	}
	/**
	 * 建索引的方法
	 */
	public void fullIndex(){
		try{
			noticeIndexDao.fullIndex(noticeDao);
		}catch(Exception ex){
			throw new SSHLException(" 建索引的方法时出现异常 ！", ex);
		}
	}
	
}
